package com.pig4cloud.pig.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.entity.MetaFieldEntity;
import com.pig4cloud.pig.admin.enums.BaseFieldType;
import com.pig4cloud.pig.admin.service.MetaFieldService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 字段表
 *
 * @author pig
 * @date 2024-09-23 17:31:09
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/metaField")
@Tag(description = "metaField", name = "字段表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class MetaFieldController {

	private final MetaFieldService metaFieldService;

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param metaField 字段表
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	@HasPermission("admin_metaField_view")
	public R getMetaFieldPage(@ParameterObject Page page, @ParameterObject MetaFieldEntity metaField) {
		LambdaQueryWrapper<MetaFieldEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(metaField.getName()), MetaFieldEntity::getName, metaField.getName());
		wrapper.like(StrUtil.isNotBlank(metaField.getLabel()), MetaFieldEntity::getLabel, metaField.getLabel());
		wrapper.eq(Objects.nonNull(metaField.getEntityId()), MetaFieldEntity::getEntityId, metaField.getEntityId());
		wrapper.eq(Objects.nonNull(metaField.getSystemFieldFlag()), MetaFieldEntity::getSystemFieldFlag, metaField.getSystemFieldFlag());
		wrapper.eq(Objects.nonNull(metaField.getDelFlag()), MetaFieldEntity::getDelFlag, metaField.getDelFlag());
		return R.ok(metaFieldService.queryMetaFieldEntityPage(page, metaField));
//		return R.ok(metaFieldService.page(page, wrapper));
	}


	/**
	 * 通过条件查询字段表
	 *
	 * @param metaField 查询条件
	 * @return R  对象列表
	 */
	@Operation(summary = "通过条件查询", description = "通过条件查询对象")
	@GetMapping("/details")
	@HasPermission("admin_metaField_view")
	public R getDetails(@ParameterObject MetaFieldEntity metaField) {
		return R.ok(metaFieldService.list(Wrappers.query(metaField)));
	}

	/**
	 * 新增字段表
	 *
	 * @param metaField 字段表
	 * @return R
	 */
	@Operation(summary = "新增字段表", description = "新增字段表")
	@SysLog("新增字段表")
	@PostMapping
	@HasPermission("admin_metaField_add")
	public R save(@RequestBody MetaFieldEntity metaField) {

		return metaFieldService.saveMetaFieldEntity(metaField);

	}

	/**
	 * 修改字段表
	 *
	 * @param metaField 字段表
	 * @return R
	 */
	@Operation(summary = "修改字段表", description = "修改字段表")
	@SysLog("修改字段表")
	@PutMapping
	@HasPermission("admin_metaField_edit")
	public R updateById(@RequestBody MetaFieldEntity metaField) {
		MetaFieldEntity entity = metaFieldService.getById(metaField.getId());
		if (ObjectUtil.isNull(entity)) {
			return R.failed("字段不存在");
		}
		if (ObjectUtil.equal(entity.getSystemFieldFlag(), CommonConstants.YES)) {
			return R.failed("系统字段不允许修改");
		}
		metaField.setLabel(null);
		metaField.setChildEntityFieldFlag(null);
		metaField.setParentIdFieldFlag(null);
		metaField.setPhysicalName(null);
		metaField.setSystemFieldFlag(null);
		return R.ok(metaFieldService.updateById(metaField));
	}

	@Operation(summary = "从回收站还原", description = "从回收站还原")
	@SysLog("修改字段表")
	@PutMapping("reduction/{id}")
	@HasPermission("admin_metaField_edit")
	public R reduction(@PathVariable Long id) {
		return R.ok(metaFieldService.reduction(id));
	}

	/**
	 * 通过id删除字段表
	 *
	 * @param ids id列表
	 * @return R
	 */
	@Operation(summary = "通过id删除字段表", description = "通过id删除字段表")
	@SysLog("通过id删除字段表")
	@DeleteMapping
	@HasPermission("admin_metaField_del")
	public R removeById(@RequestBody Long[] ids, @RequestParam(required = false) Integer delFlag) {
		if (ArrayUtil.isEmpty(ids)) {
			return R.failed("请选择要删除的数据");
		}
		if (ObjectUtil.equal(delFlag, CommonConstants.NO)) {
			List<MetaFieldEntity> metaFieldEntityList = metaFieldService.list(Wrappers.lambdaQuery(MetaFieldEntity.class).in(MetaFieldEntity::getId, ids));
			for (MetaFieldEntity metaFieldEntity : metaFieldEntityList) {
				if (ObjectUtil.equal(metaFieldEntity.getSystemFieldFlag(), CommonConstants.YES)) {
					return R.failed("系统字段不允许删除");
				}
			}
			return R.ok(metaFieldService.removeByIds(CollUtil.toList(ids)));
		} else {
			return R.ok(metaFieldService.removeMetaField(ids));
		}
	}


	/**
	 * 导出excel 表格
	 *
	 * @param metaField 查询条件
	 * @param ids       导出指定ID
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@HasPermission("admin_metaField_export")
	public List<MetaFieldEntity> exportExcel(MetaFieldEntity metaField, Long[] ids) {
		return metaFieldService.list(Wrappers.lambdaQuery(metaField).in(ArrayUtil.isNotEmpty(ids), MetaFieldEntity::getId, ids));
	}

	/**
	 * 导入excel 表
	 *
	 * @param metaFieldList 对象实体列表
	 * @param bindingResult 错误信息列表
	 * @return ok fail
	 */
	@PostMapping("/import")
	@HasPermission("admin_metaField_export")
	public R importExcel(@RequestExcel List<MetaFieldEntity> metaFieldList, BindingResult bindingResult) {
		return R.ok(metaFieldService.saveBatch(metaFieldList));
	}


	/**
	 * 获取所有字段的label
	 */
	@Operation(summary = "获取所有字段的label")
	@GetMapping("/labels")
	public R getAllFieldLabel(String entityId) {
		return R.ok(metaFieldService.list(Wrappers.lambdaQuery(MetaFieldEntity.class).eq(MetaFieldEntity::getEntityId, entityId).ne(MetaFieldEntity::getLabel, BaseFieldType.DEL_FLAG.getLabel())));
	}


}
